package com.qxp.simplerpc.application;

import com.qxp.simplerpc.proxy.CglibProxy;
import com.qxp.simplerpc.proxy.IProxy;
import com.qxp.simplerpc.proxy.JdkProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;

@Import({JdkProxy.class, CglibProxy.class})
public class SimpleRpcApplication {
    @Autowired
    private ApplicationContext applicationContext;

    private <T> T getBean(Class<?> cls, String className, String beanName) throws Exception {
        Class proxyCls = getProxyType();
        IProxy proxy = (IProxy) applicationContext.getBean(proxyCls);
        return proxy.getProxy(cls, className, beanName);
    }

    public <T> T getBean(Class<?> cls, String className) throws Exception {
        return getBean(cls, className, null);
    }

    public <T> T getBean(Class<?> cls) throws Exception {
        return this.getBean(cls, null, null);
    }

    public <T> T getBean(String beanName, Class<?> cls) throws Exception {
        return this.getBean(cls, null, beanName);
    }


    private Class<?> getProxyType() {
        String proxyType = applicationContext.getEnvironment().getProperty("proxy.type");
        if ("cglib".equals(proxyType)) {
            return CglibProxy.class;
        }
        return JdkProxy.class;
    }

}
